import '@nutui/nutui-react-taro/dist/style.css'
import { View } from '@tarojs/components'
import Taro, { useDidHide, useDidShow } from '@tarojs/taro'
import { useEffect } from 'react'
import { useLogin, useStorage } from 'taro-hooks'
import './app.less'
import './assets/font/iconfont.css'
import { CLOUD_CONFIG } from './services/config'
import { onLogin } from './services/login'
import { AuthProvider } from './stores/auth'
import { useTabBarStore } from './stores/tabbar'

function App(props) {
  // 获取 TabBar store 的初始化方法
  const { check, login } = useLogin()
  Taro.cloud.init({
    env: CLOUD_CONFIG.env,
  })
  const [_, { set, get }] = useStorage()

  const initTabBar = useTabBarStore((state) => state.initTabBar)

  useEffect(() => {
    check()
      .then(() => {
        get('code').then((code: any) => {
          // 走业务登录
          onLogin(code).then((_res: any) => {})
        })
      })
      .catch(() => {
        login().then((loginRes: any) => {
          const code = loginRes.code
          set('code', code)
          if (loginRes) {
            // 走业务登录
            onLogin(code).then((_res: any) => {})
          }
        })
      })
    // 初始化 TabBar 状态
    initTabBar()
  }, [])

  useDidShow(() => {})

  useDidHide(() => {})

  return (
    <AuthProvider>
      <View className='app'>{props.children}</View>
    </AuthProvider>
  )
}

export default App
